/*
 * AjaxScrollLoad for jQuery
 * By Gideon Amissah
 *
 */

(function($){
    var AjaxScroll = function(el,params){
        if(el && el.length > 0){
            this.element = el;
            this.init(params);
        }
    }
    AjaxScroll.prototype.init = function(params){
        var self = this;
        var p = $.extend({processing:false,load_limit:9,load_page:1,total_pages:100,buffer:40,url:'',search_element:null,callback:null},params);
        this.buffer =  p.buffer;//amount from the bottom of the scroll to be used for scrolling
        this.callback = p.callback;
        this.processing = p.processing;
        this.load_limit = p.load_limit;
        this.load_page = p.load_page;
        this.total_pages = p.total_pages;
        this.url = p.url;
        this.search_element = p.search_element;
        this.search_btn = p.search_btn;
        this.clear_btn = p.clear_btn;
        $(self.element).scroll(function (e) {
            self.checkScroll();
        });
        //Bind the search and clear buttons
        if(this.search_btn && this.search_btn.length > 0){
            this.search_btn.click(function (e) {
                var query = self.search_element.val();
                query = query.trim();
                if (query.length > 0) {
                    self.load_page = 1;
                    self.loadContent();
                }
            });
        }
        if(this.clear_btn && this.clear_btn.length > 0){
            this.clear_btn.click(function (e) {
                var query = self.search_element.val();
                query = query.trim();
                if (query.length > 0) {
                    self.search_element.val('');
                    self.element.html('');
                    self.load_page = 1;
                    self.total_pages = 100;
                    self.loadContent();
                }
            });
        }
        //Load the content once.
        self.loadContent();
    }

    AjaxScroll.prototype.checkScroll = function(){
        var scroll_height = this.element.prop('scrollHeight');
        var scroll_top = this.element.scrollTop();
        var ul_height = this.element.height();
        var scroll = scroll_height - scroll_top;
        var height = ul_height + this.buffer;

        if (scroll <= height) {

            var next_page = this.load_page - 1;
            var total_pages = this.total_pages;
            if (next_page < total_pages) {
                if (!this.processing) {
                    this.loadContent();
                }
            }

        }
    }

    AjaxScroll.prototype.loadContent = function(){
        var self = this;
        self.processing = true;
        var search = self.search_element.val();
        search = search.trim();
        var query = "page=" + self.load_page + "&limit=" + self.load_limit + "&query=" + search;

        $.ajax({
            type: 'post',
            url: this.url,
            data: query,
            dataType: 'json',
            success: function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    var messages = response.msg;
                    var len = messages.length;
                    for (var x = 0; x < len; x++) {
                        txt += messages[x] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                if (response.code == 0) {
                    if(typeof this.callback == 'function'){
                        this.callback();
                    }
                    self.appendContent(response, search)
                }
                else {
                    self.element.html('');
                    jLib.serverError(txt);
                }
            },
            error: function () {
                jLib.serverError();
            }
        });
    }


    AjaxScroll.prototype.appendContent = function(param, query){
        var self = this;
        var data = param.rows;
        if (query.length > 0) {
            self.element.html('');
        }
        var len = data.length;
        for (var x = 0; x < len; x++) {
            var li = $('<li />').addClass('unread').attr('data-id', data[x].id);
            var summary = $('<div />').addClass('summary');
            var date = $('<span />').addClass('date pull-right').html($('<span />').html(data[x].date));
            var hiring_number = $('<h4 />').html(data[x].hiring_number);
            var customer = $('<p />').html(" <strong>" + data[x].customer + "</strong> - Cost GHS " + data[x].cost_of_hiring);
            li.append(summary.append(date).append(hiring_number).append(customer));
            self.element.append(li);
        }
        // console.log(data);
        self.processing = false;
        self.load_page = self.load_page + 1;
        self.total_pages = param.total_pages;
    }


    $.fn.ajax_scroll  = function(params){
        return $(this).each(function () {
            var obj = new AjaxScroll($(this),params);
        });
    };
})(jQuery);